package com.eqdd.yiqidian.ui.yiqigou

import android.app.Activity
import android.content.Intent
import android.support.v7.widget.LinearLayoutManager
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import chihane.jdaddressselector.BottomDialog
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector
import com.eqdd.yiqidian.base.BaseActivity
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.AreaBean
import com.eqdd.yiqidian.bean.CompanyDemandBean
import com.eqdd.yiqidian.bean.utils.MultiChooseBean
import com.eqdd.yiqidian.box.ItemDecoration.DividerLineItemDecoration
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource
import com.eqdd.yiqidian.http.DialogCallBack
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.http.JsonConverter
import com.eqdd.yiqidian.kotlin.popMenu
import com.eqdd.yiqidian.ui.SingleChooseActivity
import com.eqdd.yiqidian.ui.companyspace.ProDemandInfoActivity
import com.eqdd.yiqidian.utils.MultiChooseTestUtil
import com.eqdd.yiqidian.utils.TimeUtil
import com.lzy.okgo.OkGo
import com.lzy.okgo.cache.CacheMode
import com.lzy.okgo.model.HttpParams
import com.lzy.okgo.model.Response
import com.lzy.okrx2.adapter.FlowableBody
import com.shizhefei.mvc.MVCCoolHelper
import io.reactivex.Flowable
import kotlinx.android.synthetic.main.activity_recyclerview_refresh_search.*
import kotlinx.android.synthetic.main.activity_title.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.startActivityForResult
import java.util.*

/**
 * Created by jhj on 18-8-18.
 */
class RequestSearchActivity : BaseActivity() {


    private var pageNum = 0
    private var isAllData = false
    private var position: String = ""
    private var demandType: String = ""
    private var areaBean: List<AreaBean>? = null
    private var areaDialog: BottomDialog? = null
    private var inputManager: InputMethodManager? = null
    private var slimAdapterEx: SlimAdapterEx<CompanyDemandBean>? = null
    private var mvcHelper: MVCCoolHelper<List<CompanyDemandBean>>? = null

    override fun initBinding() {
        setContentView(R.layout.activity_recyclerview_refresh_search)
        initTopTitleBar(View.VISIBLE, "搜索")
        tv_right.text = "筛选"
        popMenu(arrayListOf("产品类别", "产品地区", "重置筛选"), tv_right) { dialog, pos ->
            if (pos == 0) {
                startActivityForResult<SingleChooseActivity>(1000, Config.TITLE to "产品类别", Config.TYPE to 2)
            } else if (pos == 1) {
                initAreaDialog()
            } else {
                position = ""
                demandType = ""
                mvcHelper?.refresh()
            }
        }
        searchBarMask.setOnTouchListener(keyboardState)

    }

    override fun initData() {

        val list = arrayListOf<CompanyDemandBean>()
        mvcHelper = MVCCoolHelper<List<CompanyDemandBean>>(coolRefreshView)
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.addItemDecoration(DividerLineItemDecoration(this))
        slimAdapterEx = SlimAdapterEx.create().register<CompanyDemandBean>(R.layout.layout_list_demand, object : SlimInjector<CompanyDemandBean> {
            override fun onInject(data: CompanyDemandBean?, injector: IViewInjector<out IViewInjector<*>>?) {

                val array = data?.EndTime?.split("/", " ", ":", "-")
                val calendar = Calendar.getInstance()
                var status = ""
                array?.let {
                    if (it.size > 2) {
                        calendar.set(it[0].toInt(), it[1].toInt() - 1, it[2].toInt(), 23, 59, 59)
                    }
                    val a = calendar.timeInMillis
                    val b = Calendar.getInstance().timeInMillis

                    status = if (a > b) {
                        "（进行中）"
                    } else {
                        "（已结束）"
                    }
                }
                injector
                        ?.text(R.id.tv_demand_time, String.format(Locale.CHINA, "发布时间：%s${status}", TimeUtil.formatWebTime1(data?.createTime)))
                        ?.text(R.id.tv_demand_label, String.format(Locale.CHINA, "产品描述：%s", data?.ProductDesc))
                        ?.visibility(R.id.tv_demand_label, if (data?.ProductDesc.isNullOrBlank()) View.GONE else View.VISIBLE)
                if (isAllData) {
                    injector?.text(R.id.tv_demand_title, data?.ProductName)
                            ?.visibility(R.id.tv_demand_title, if (data?.ProductName.isNullOrBlank()) View.GONE else View.VISIBLE)
                            ?.text(R.id.tv_demand_budget, String.format(Locale.CHINA, "需求预算：%s", data?.DemandPrice))
                            ?.visibility(R.id.tv_demand_budget, if (data?.DemandPrice.isNullOrBlank()) View.GONE else View.VISIBLE)
                            ?.text(R.id.tv_demand_count, String.format(Locale.CHINA, "需求量：%s", data?.DemandNum))
                            ?.visibility(R.id.tv_demand_count, if (data?.DemandNum.isNullOrBlank()) View.GONE else View.VISIBLE)
                            ?.text(R.id.tv_demand_address, String.format(Locale.CHINA, "发货地址：%s", data?.DemandAddress))
                            ?.visibility(R.id.tv_demand_address, if (data?.DemandAddress.isNullOrBlank()) View.GONE else View.VISIBLE)
                } else {
                    injector?.text(R.id.tv_demand_title, data?.productName)
                            ?.visibility(R.id.tv_demand_title, if (data?.productName.isNullOrBlank()) View.GONE else View.VISIBLE)
                            ?.text(R.id.tv_demand_budget, String.format(Locale.CHINA, "需求预算：%s", data?.demandPrice))
                            ?.visibility(R.id.tv_demand_budget, if (data?.demandPrice.isNullOrBlank()) View.GONE else View.VISIBLE)
                            ?.text(R.id.tv_demand_count, String.format(Locale.CHINA, "需求量：%s", data?.demandNum))
                            ?.visibility(R.id.tv_demand_count, if (data?.demandNum.isNullOrBlank()) View.GONE else View.VISIBLE)
                            ?.text(R.id.tv_demand_address, String.format(Locale.CHINA, "发货地址：%s", data?.demandAddress))
                            ?.visibility(R.id.tv_demand_address, if (data?.demandAddress.isNullOrBlank()) View.GONE else View.VISIBLE)
                }
            }
        }).attachTo(recyclerView).updateData(list as List<CompanyDemandBean>?) as SlimAdapterEx<CompanyDemandBean>?
        ItemClickSupport.addTo(recyclerView)
                .setOnItemClickListener { recyclerView, position, v ->
                    val data = slimAdapterEx?.getDataItem(position)
                    startActivity<ProDemandInfoActivity>(Config.ID to data?.Id, Config.TYPE to 2, "fun" to 2)
                }

        requestData()
    }

    private fun requestData() {
        val dataSource = ModelRx2DataSource<CompanyDemandBean>(ModelRx2DataSource.OnLoadSource<CompanyDemandBean> { page, register ->
            val params = HttpParams()

            val url = if (et_search?.text.isNullOrBlank() && position == "" && demandType == "") {
                isAllData = true
                HttpConfig.BASE_URL + HttpConfig.DEMAND_LIST
            } else {
                isAllData = false
                params.put("para", et_search.text?.toString() ?: "")
                params.put("demandType", demandType)
                params.put("area", position)
                HttpConfig.BASE_URL + HttpConfig.DEMAND_SEARCH
            }

            if (page == 1) {
                pageNum = 0
            }
            OkGo.post<HttpResult<List<CompanyDemandBean>>>(url)
                    .params("page", pageNum)
                    .params("companyId", user.companyId)
                    .params(params)
                    .converter(object : JsonConverter<HttpResult<List<CompanyDemandBean>>>() {
                        override fun test() {
                            super.test()
                        }
                    })
                    .adapt(FlowableBody<HttpResult<List<CompanyDemandBean>>>())
                    .flatMap({ result ->
                        pageNum = result.page
                        Flowable.just(
                                if (result.items == null) arrayListOf<CompanyDemandBean>() else result.items
                        )
                    })

        }, 10)

        mvcHelper?.setDataSource(dataSource)
        mvcHelper?.adapter = slimAdapterEx
        mvcHelper?.refresh()
    }

    override fun setView() {
        et_search.setOnKeyListener { v, keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_DOWN) {
                (inputManager as InputMethodManager?)?.hideSoftInputFromWindow(et_search.windowToken, 0)
                mvcHelper?.refresh()
            }
            false
        }
    }

    private val keyboardState = View.OnTouchListener { _, _ ->
        searchBarMask.visibility = View.GONE
        et_search.addTextChangedListener(textChangedListener)

        if (inputManager == null) {
            inputManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
            inputManager?.showSoftInput(et_search, InputMethodManager.SHOW_FORCED)
        }
        coolRefreshView.setOnTouchListener { _, _ ->
            (inputManager as InputMethodManager?)?.hideSoftInputFromWindow(et_search.windowToken, 0)
            if (et_search.text.isNullOrBlank()) {
                searchBarMask.visibility = View.VISIBLE
            }
            false
        }
        false
    }

    private val textChangedListener = object : TextWatcher {
        override fun afterTextChanged(p0: Editable?) {
            if (et_search.text.isNullOrBlank()) {
                tv_right.visibility = View.GONE
                position = ""
                demandType = ""
                requestData()
            } else {
                tv_right.visibility = View.VISIBLE
            }
        }

        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
        }

        override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

        }

    }

    private fun initAreaDialog() {
        if (areaDialog == null) {
            OkGo.post<List<AreaBean>>(HttpConfig.BASE_URL + HttpConfig.AREA_OPTIONS)
                    .params("type", 0)
                    .cacheMode(CacheMode.IF_NONE_CACHE_REQUEST)
                    .cacheKey(HttpConfig.BASE_URL + HttpConfig.AREA_OPTIONS + "0")
                    .execute(object : DialogCallBack<List<AreaBean>>(this) {
                        override fun onSuccess(response: Response<List<AreaBean>>) {
                            areaBean = response.body()
                            initAreaPicker()
                        }

                        override fun onCacheSuccess(response: Response<List<AreaBean>>?) {
                            super.onCacheSuccess(response)
                            areaBean = response?.body()
                            initAreaPicker()
                        }
                    })
        } else {
            areaDialog?.show()
        }
    }


    private fun initAreaPicker() {
        val multiChooseBeen = ArrayList<MultiChooseBean>()
        areaBean?.let {
            multiChooseBeen.addAll(it)
        }
        areaDialog = MultiChooseTestUtil().getAreaDialog(this@RequestSearchActivity, 3, multiChooseBeen) { d, a ->
            areaDialog?.dismiss()
            position = ""
            for (iSelectAble in a) {
                position += iSelectAble.name
            }
            mvcHelper?.refresh()
        }
        areaDialog?.show()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1000 && resultCode == Activity.RESULT_OK) {
            demandType = data?.getStringExtra("data") ?: ""
            mvcHelper?.refresh()
        }
    }

}